package com.newbee.adapter;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceActivity.Header;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.hhu.newbee.R;
import com.newbee.activity.tab.ConfigActivity;
import com.newbee.app.AppConfig;
import com.newbee.app.SpeechApp;
import com.newbee.http.ServerHttpUtil;
import com.newbee.listbean.FriendsInfoBean;
import com.newbee.round.CustomImageView;

public class FriendsListvewAdapter extends BaseAdapter
{

	private List<FriendsInfoBean> list;
	private Context context;
	public static final Map<String, SoftReference<Bitmap>> bitmapMap = new HashMap<String, SoftReference<Bitmap>>();

	public void setList(List<FriendsInfoBean> list)
	{
		this.list = list;
	}

	public FriendsListvewAdapter(List<FriendsInfoBean> list, Context context)
	{
		this.list = list;
		this.context = context;
	}

	@Override
	public int getCount()
	{
		if (list != null)
		{
			return list.size();
		}
		else
		{
			return 0;
		}

	}

	@Override
	public Object getItem(int item)
	{
		return item;
	}

	@Override
	public long getItemId(int item)
	{
		// TODO Auto-generated method stub
		return item;
	}

	@SuppressLint("ResourceAsColor")
	@Override
	public View getView(int position, View view, ViewGroup arg2)
	{
		final LayoutViewBean layout = new LayoutViewBean();

		if (view == null)
		{
			view = LayoutInflater.from(context).inflate(
					R.layout.listitem_friends, null);
		}
		layout.email = (TextView) view.findViewById(R.id.friends_email);
		layout.nickName = (TextView) view.findViewById(R.id.friends_nickname);
		layout.state = (TextView) view.findViewById(R.id.friends_state);
		layout.headView = (CustomImageView) view
				.findViewById(R.id.friends_head);
		FriendsInfoBean fib = list.get(position);

		String st = fib.getEmail();

		String[] array = st.split("\\$");

		layout.email.setText(array[0].replace('#', '@'));
		if (fib.isState())
		{
			layout.state.setText("[在线]");
			layout.state.setTextColor(context.getResources().getColor(
					R.color.steelblue));
		}
		else
		{
			layout.state.setText("[离线]");
			layout.state.setTextColor(context.getResources().getColor(
					R.color.black));
		}

		try
		{
			String username = (String) SpeechApp.getUserNamePair()
					.get(array[0]);
			layout.nickName.setText(username);
		}
		catch (JSONException e1)
		{
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		final String picNameNOPng = array[2].split("@")[0];

		SoftReference<Bitmap> img = bitmapMap.get(picNameNOPng);

		layout.headView.setTag(picNameNOPng);
		File file = new File(Environment.getExternalStorageDirectory()
				+ SpeechApp.HEAD_FILE + "/" + picNameNOPng + ".png");
		if (img != null)
		{
			Bitmap bitmap = img.get();
			if (bitmap != null)
			{
				layout.headView.setmSrc(bitmap);
				layout.headView.postInvalidate();
			}
			else
			{

				if (file.exists())
				{

					try
					{
						FileInputStream fis = new FileInputStream(file);
						bitmap = BitmapFactory.decodeStream(fis);
						layout.headView.setmSrc(bitmap);
						layout.headView.postInvalidate();
						fis.close();
					}
					catch (Exception e)
					{
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}
				else
				{
					new Thread()
					{
						public void run()
						{

							try
							{
								InputStream is = new URL(AppConfig.HTTP
										+ ServerHttpUtil.HEAD_dir
										+ picNameNOPng + ".png").openStream();

								Bitmap img = BitmapFactory.decodeStream(is);

								layout.headView.setmSrc(img);
								layout.headView.postInvalidate();

								bitmapMap.put(picNameNOPng,
										new SoftReference<Bitmap>(img));

								FileOutputStream fis = new FileOutputStream(
										new File(Environment
												.getExternalStorageDirectory()
												+ SpeechApp.HEAD_FILE
												+ "/"
												+ picNameNOPng + ".png"));
								img.compress(Bitmap.CompressFormat.PNG, 100,
										fis);
								fis.close();

							}
							catch (MalformedURLException e)
							{
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							catch (IOException e)
							{
								// TODO Auto-generated catch block
								e.printStackTrace();
							}

						};

					}.start();

				}

			}
		}
		else
		{

			if (file.exists())
			{

				try
				{
					FileInputStream fis = new FileInputStream(file);
					Bitmap bitmap = BitmapFactory.decodeStream(fis);
					layout.headView.setmSrc(bitmap);
					layout.headView.postInvalidate();
					fis.close();
				}
				catch (Exception e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
			else
			{
				new Thread()
				{
					public void run()
					{

						try
						{
							InputStream is = new URL(AppConfig.HTTP
									+ ServerHttpUtil.HEAD_dir + picNameNOPng
									+ ".png").openStream();

							Bitmap img = BitmapFactory.decodeStream(is);

							layout.headView.setmSrc(img);
							layout.headView.postInvalidate();

							bitmapMap.put(picNameNOPng,
									new SoftReference<Bitmap>(img));

							FileOutputStream fis = new FileOutputStream(
									new File(Environment
											.getExternalStorageDirectory()
											+ SpeechApp.HEAD_FILE
											+ "/"
											+ picNameNOPng + ".png"));
							img.compress(Bitmap.CompressFormat.PNG, 100, fis);
							fis.close();

						}
						catch (MalformedURLException e)
						{
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						catch (IOException e)
						{
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					};

				}.start();

			}

		}

		return view;
	}

	static class LayoutViewBean
	{
		TextView nickName;
		// ImageView head;
		CustomImageView headView;
		TextView email;
		TextView state;

	}

}
